﻿angular.module('paperless').controller('transactionEditController', function ($scope, Restangular, $stateParams, $q, $state) {
    'use strict';

    var promises = {};

    $scope.transaction = {};

    if ($stateParams.id) {
        promises.transaction = Restangular.one('transaction', $stateParams.id).get().then(function (transaction) {
            $scope.transaction = transaction;

            $scope.hasOutsideAgents = (transaction.outsideListingAgent || transaction.outsideSellingAgent) && true;

            return transaction;
        });
    }

    promises.status = Restangular.all('status').getList().then(function (status) {
        $scope.status = status;
    });

    promises.location = Restangular.all('location').getList().then(function (locations) {
        $scope.locations = locations;
    });

    promises.agent = Restangular.all('user').getList({ locationId: 1 }).then(function (agents) {
        $scope.agents = agents;
    });

    $scope.addTransaction = function (transaction) {
        transaction.assignAgents =
            $scope.agents
                .filter(function (agent) {
                    return agent.listing || agent.selling;
                })
                .map(function (agent) {
                    agent = Restangular.stripRestangular(agent);
                    agent.userId = agent.id;
                    agent.id = undefined;
                    return agent;
                });

        Restangular.all('transaction').post(transaction).then(function () {
            $state.transitionTo('transaction');
        });
    };

    $scope.updateTransaction = function (transaction) {
        transaction.assignAgents =
            $scope.agents
                .filter(function (agent) {
                    return agent.listing || agent.selling;
                })
                .map(function (agent) {
                    agent = Restangular.stripRestangular(agent);
                    agent.userId = agent.id;
                    agent.id = undefined;
                    return agent;
                });

        transaction.put().then(function () {
            $state.transitionTo('transaction');
        });
    };

    $q.all(promises).then(function () {
        if ($scope.transaction.assignAgents) {
            $scope.agents.forEach(function (agent) {
                $scope.transaction.assignAgents.forEach(function (assignAgent) {
                    if (assignAgent.userId == agent.id) {
                        agent.listing = assignAgent.listing;
                        agent.selling = assignAgent.selling;

                        return false;
                    }
                });
            });
        }

        console.log('loaded');
    });
});